package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

//定义获取Mapper接口实现类对象的工具类
public class MapperUtil {
    private static SqlSessionFactory sqlSessionFactory;
    //保证线程安全,定义ThreadLocal
    private static ThreadLocal<SqlSession> sqlSessionThreadLocal = new ThreadLocal<>();

    //静态代码块
    static {
        try {
            //创建SqlSessionFactoryBuilder类的对象,作用创建SqlSessionFactory工厂对象的
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //通过类加载器获取核心配置文件的字节输入流对象
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            //使用SqlSessionFactoryBuilder类的对象调用build方法,创建创建SqlSessionFactory工厂对象
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //定义方法获取Mapper接口实现类对象
    public static <T> T getMapper(Class<T> mapperClazz) {
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            sqlSessionThreadLocal.set(sqlSession);
        }
        return sqlSession.getMapper(mapperClazz);
    }

    //定义方法关闭资源
    //查询操作不需要事务,直接关闭
    public static void close() {
        sqlSessionThreadLocal.get().close();
        sqlSessionThreadLocal.remove();
    }

    //定义方法提交事务并关闭资源
    //增删改需要提交事务: 先提交,再关闭
    public static void commitAndClose() {
        sqlSessionThreadLocal.get().commit();
        sqlSessionThreadLocal.get().close();
        sqlSessionThreadLocal.remove();
    }

    //定义方法回滚事务并关闭资源
    //增删改有问题需要回滚事务: 先回滚,再关闭
    public static void rollbackAndClose() {
        sqlSessionThreadLocal.get().rollback();
        sqlSessionThreadLocal.get().close();
        sqlSessionThreadLocal.remove();
    }
}
